<template>
  <div class="prediction-container">
    <!-- 页面标题区 -->
    <div class="page-header">
      <el-icon class="header-icon"><Activity /></el-icon>
      <h1>糖尿病风险预测</h1>
      <p class="header-desc">通过输入健康数据，评估您的糖尿病患病风险，提供个性化健康建议</p>
    </div>

    <!-- 主内容区：采用网格布局增强层次感 -->
    <div class="main-content">
      <!-- 预测表单卡片 -->
      <el-card class="prediction-form card-shadow">
        <template #header>
          <div class="card-header">
            <el-icon class="card-icon"><Edit /></el-icon>
            <span>输入健康数据</span>
          </div>
        </template>

        <el-form :model="predictionForm" label-width="180px" class="form-grid">
          <!-- 表单采用两列网格布局，提升空间利用率 -->
          <el-form-item
              label="怀孕次数"
              class="form-item"
              tooltip="女性怀孕次数（未怀孕或男性请填0）"
          >
            <el-input-number
                v-model="predictionForm.pregnancies"
                :min="0"
                :max="20"
                class="form-input"
                placeholder="请输入"
            />
          </el-form-item>

          <el-form-item
              label="血糖浓度(mg/dL)"
              class="form-item"
              tooltip="空腹血糖正常值：70-100mg/dL"
          >
            <el-input-number
                v-model="predictionForm.glucose"
                :min="0"
                :max="300"
                class="form-input"
                placeholder="请输入"
            />
            <span class="normal-range">正常范围: 70-100</span>
          </el-form-item>

          <el-form-item
              label="血压(mm Hg)"
              class="form-item"
              tooltip="舒张压正常值：60-80mm Hg"
          >
            <el-input-number
                v-model="predictionForm.bloodPressure"
                :min="0"
                :max="200"
                class="form-input"
                placeholder="请输入"
            />
            <span class="normal-range">正常范围: 60-80</span>
          </el-form-item>

          <el-form-item
              label="皮肤厚度(mm)"
              class="form-item"
              tooltip="三头肌皮褶厚度，评估体脂率的指标"
          >
            <el-input-number
                v-model="predictionForm.skinThickness"
                :min="0"
                :max="100"
                class="form-input"
                placeholder="请输入"
            />
          </el-form-item>

          <el-form-item
              label="胰岛素水平(mu U/ml)"
              class="form-item"
              tooltip="空腹胰岛素水平，反映胰岛功能"
          >
            <el-input-number
                v-model="predictionForm.insulin"
                :min="0"
                :max="1000"
                class="form-input"
                placeholder="请输入"
            />
          </el-form-item>

          <el-form-item
              label="BMI指数"
              class="form-item"
              tooltip="身体质量指数 = 体重(kg) ÷ 身高(m)²"
          >
            <el-input-number
                v-model="predictionForm.bmi"
                :min="0"
                :max="100"
                :step="0.1"
                class="form-input"
                placeholder="请输入"
            />
            <span class="normal-range">正常范围: 18.5-23.9</span>
          </el-form-item>

          <el-form-item
              label="糖尿病遗传函数"
              class="form-item"
              tooltip="基于家族病史的遗传风险系数"
          >
            <el-input-number
                v-model="predictionForm.diabetesPedigree"
                :min="0"
                :max="5"
                :step="0.01"
                class="form-input"
                placeholder="请输入"
            />
          </el-form-item>

          <el-form-item
              label="年龄"
              class="form-item"
          >
            <el-input-number
                v-model="predictionForm.age"
                :min="0"
                :max="120"
                class="form-input"
                placeholder="请输入"
            />
          </el-form-item>

          <el-form-item class="form-actions">
            <el-button
                type="primary"
                @click="predictDiabetes"
                :loading="isPredicting"
                class="btn-predict"
            >
              <el-icon v-if="isPredicting"><Loading /></el-icon>
              <span v-else><MagicStick /></span>
              开始预测
            </el-button>
            <el-button @click="resetForm" class="btn-reset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 预测结果卡片：添加淡入动画 -->
      <transition name="fade-in">
        <el-card
            class="prediction-result card-shadow"
            v-if="showResult"
        >
          <template #header>
            <div class="card-header">
              <el-icon class="card-icon">
                <CheckCircle v-if="!isDiabetic" />
                <Warning v-if="isDiabetic" />
              </el-icon>
              <span>预测结果</span>
            </div>
          </template>

          <div class="result-content">
            <!-- 结果状态标签 -->
            <div class="result-status">
              <span
                  class="status-badge"
                  :class="isDiabetic ? 'status-high' : 'status-low'"
              >
                {{ isDiabetic ? '高风险' : '低风险' }}
              </span>
              <el-alert
                  :title="resultTitle"
                  :type="resultType"
                  :description="resultDescription"
                  show-icon
                  :closable="false"
                  class="result-alert"
              />
            </div>

            <!-- 风险进度条与详情 -->
            <div class="result-details">
              <div class="risk-meter">
                <div class="risk-labels">
                  <span>低风险</span>
                  <span>中风险</span>
                  <span>高风险</span>
                </div>
                <el-progress
                    :percentage="predictionProbability * 100"
                    :status="resultProgressStatus"
                    :stroke-width="10"
                    :format="progressFormat"
                    class="risk-progress"
                />
              </div>

              <!-- 健康建议：增加图标与分点 -->
              <div class="health-advice">
                <h3 class="advice-title">
                  <el-icon><Lightbulb /></el-icon>
                  健康建议
                </h3>
                <ul class="advice-list">
                  <li v-for="(item, index) in adviceList" :key="index">
                    <el-icon class="advice-icon">{{ item.icon }}</el-icon>
                    {{ item.text }}
                  </li>
                </ul>
              </div>
            </div>
          </div>
        </el-card>
      </transition>

      <!-- 数据可视化卡片 -->
      <el-card class="data-visualization card-shadow">
        <template #header>
          <div class="card-header">
            <el-icon class="card-icon"><BarChart /></el-icon>
            <span>历史预测数据</span>
            <div class="chart-controls">
              <el-button-group size="small">
                <el-button
                    :type="chartType === 'line' ? 'primary' : ''"
                    @click="changeChartType('line')"
                    icon="LineChart"
                >
                  折线图
                </el-button>
                <el-button
                    :type="chartType === 'bar' ? 'primary' : ''"
                    @click="changeChartType('bar')"
                    icon="BarChart"
                >
                  柱状图
                </el-button>
                <el-button
                    :type="chartType === 'pie' ? 'primary' : ''"
                    @click="changeChartType('pie')"
                    icon="PieChart"
                >
                  饼图
                </el-button>
              </el-button-group>
              <el-button
                  size="small"
                  type="success"
                  @click="exportChartData"
                  icon="Download"
              >
                导出数据
              </el-button>
              <el-button
                  size="small"
                  type="danger"
                  @click="clearHistoryData"
                  icon="Delete"
              >
                清除历史
              </el-button>
            </div>
          </div>
        </template>

        <!-- 图表容器：添加背景网格与提示 -->
        <div class="chart-container">
          <canvas ref="chartCanvas"></canvas>
          <div class="chart-placeholder" v-if="historyData.length === 0">
            <el-empty
                description="暂无历史数据，完成预测后将显示在此处"
                :image-size="100"
            />
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import {computed, ref, onMounted} from 'vue';
import {
   Edit,  Warning, MagicStick, Refresh,
  Loading, PieChart, Download, Delete, Apple, User
} from "@element-plus/icons-vue";
import { Chart } from 'chart.js/auto';
import {ElMessage, ElEmpty} from "element-plus";

// 新增：预测加载状态
const isPredicting = ref(false);

// API配置（保持不变）
const predictionApiUrl = 'http://your-api-server.com/predict';
const apiConfig = {
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer your-access-token'
  }
};

// 预测表单数据（保持不变）
const predictionForm = ref({
  pregnancies: 0,
  glucose: 100, // 增加合理默认值
  bloodPressure: 70,
  skinThickness: 20,
  insulin: 80,
  bmi: 22,
  diabetesPedigree: 0.3,
  age: 45
});

// 预测结果相关（保持不变）
const showResult = ref(false);
const predictionProbability = ref<number | null>(null);
const isDiabetic = ref(false);

// 预测糖尿病：新增加载状态
const predictDiabetes = async () => {
  // 表单验证
  const formValues = Object.values(predictionForm.value);
  if (formValues.some(v => v === 0 && formValues.indexOf(v) !== 0)) { // 允许怀孕次数为0
    ElMessage.warning('请完善健康数据后再进行预测');
    return;
  }

  isPredicting.value = true;
  try {
    // 模拟预测延迟
    await new Promise(resolve => setTimeout(resolve, 800));

    // 模拟预测结果（保持不变）
    predictionProbability.value = Math.random();
    isDiabetic.value = predictionProbability.value > 0.5;
    showResult.value = true;

    // 添加到历史数据（保持不变）
    const now = new Date();
    const dateStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
    historyData.value.push({
      date: dateStr,
      probability: predictionProbability.value
    });

    // 更新图表并保存数据（保持不变）
    if (chart.value) {
      chart.value.data.labels = historyData.value.map(item => item.date);
      chart.value.data.datasets[0].data = historyData.value.map(item => item.probability * 100);
      chart.value.update();
    }
    saveHistoryData();

  } catch (error) {
    console.error('预测失败:', error);
    ElMessage.error('预测失败，请稍后重试');
  } finally {
    isPredicting.value = false;
  }
};

// 重置表单（保持不变）
const resetForm = () => {
  predictionForm.value = {
    pregnancies: 0,
    glucose: 100,
    bloodPressure: 70,
    skinThickness: 20,
    insulin: 80,
    bmi: 22,
    diabetesPedigree: 0.3,
    age: 45
  };
  showResult.value = false;
  predictionProbability.value = null;
  ElMessage.success('表单已重置');
};

// 计算属性：优化结果文案，更专业
const resultTitle = computed(() => {
  return isDiabetic.value
      ? '您有较高的糖尿病患病风险'
      : '您的糖尿病患病风险较低';
});

const resultType = computed(() => {
  return isDiabetic.value ? 'warning' : 'success';
});

const resultDescription = computed(() => {
  return isDiabetic.value
      ? '根据您的健康数据，您可能存在糖尿病风险，建议尽快到医院进行空腹血糖和糖化血红蛋白检测。'
      : '根据您的健康数据，您的糖尿病风险较低，但仍需保持健康的生活方式，定期监测血糖。';
});

// 新增：健康建议列表，结合图标增强可读性
const adviceList = computed(() => {
  if (predictionProbability.value < 0.3) {
    return [
      { text: '保持低GI饮食，减少精制糖摄入' },
      { text: '每周至少进行150分钟中等强度有氧运动' },
      { text: '每年进行一次常规体检，监测血糖变化' }
    ];
  } else if (predictionProbability.value < 0.6) {
    return [
      { text: '控制每日热量摄入，减少高糖、高脂食物' },
      { text: '每周进行3-5次有氧运动，每次30分钟以上' },
      { text: '每6个月检测一次空腹血糖和BMI' }
    ];
  } else {
    return [
      {  text: '建议3个月内到内分泌科就诊，进行糖尿病确诊检查' },
      { icon: Apple, text: '立即开始糖尿病饮食管理，严格控制碳水化合物摄入' },
      { text: '在医生指导下进行适度运动，避免剧烈活动' },
      { icon: User, text: '定期监测空腹和餐后2小时血糖，记录变化趋势' }
    ];
  }
});

// 其余计算属性（保持不变）
const resultProgressStatus = computed(() => {
  return predictionProbability.value! > 0.7 ? 'exception' :
      predictionProbability.value! > 0.3 ? 'warning' : 'success';
});

const progressFormat = () => {
  return `${(predictionProbability.value! * 100).toFixed(1)}% 患病概率`;
};

// 图表相关：优化图表样式与交互
const chartCanvas = ref<HTMLCanvasElement | null>(null);
const chart = ref<Chart | null>(null);
const chartType = ref<'line' | 'bar' | 'pie'>('line');

// 切换图表类型（优化图表配色）
const changeChartType = (type: 'line' | 'bar' | 'pie') => {
  chartType.value = type;
  if (chart.value) {
    chart.value.destroy();
    chart.value = new Chart(chartCanvas.value!, {
      type: chartType.value,
      data: {
        labels: historyData.value.map(item => item.date),
        datasets: [{
          label: '糖尿病风险概率(%)',
          data: historyData.value.map(item => item.probability * 100),
          borderColor: '#30B0C7', // 主色调统一
          backgroundColor: chartType.value === 'pie'
              ? ['#30B0C7', '#67C23A', '#E6A23C', '#F56C6C', '#909399']
              : 'rgba(48, 176, 199, 0.3)',
          borderWidth: 2,
          tension: 0.3, // 更柔和的曲线
          fill: chartType.value !== 'pie',
          // 图表点样式
          pointBackgroundColor: '#fff',
          pointBorderColor: '#30B0C7',
          pointBorderWidth: 2,
          pointRadius: 4,
          pointHoverRadius: 6
        }]
      },
      options: {
        responsive: true,
        interaction: { // 增强交互体验
          mode: 'index',
          intersect: false,
          hover: {
            delay: 200,
            backgroundColor: 'rgba(255, 255, 255, 0.9)',
            titleColor: '#333',
            bodyColor: '#666',
            borderColor: '#ddd',
            borderWidth: 1,
            padding: 10,
            boxPadding: 5
          }
        },
        plugins: {
          legend: {
            position: 'top',
            labels: {
              usePointStyle: true,
              pointStyle: 'circle'
            }
          },
          tooltip: {
            callbacks: {
              label: function(context) {
                return `风险概率: ${context.raw}%`;
              }
            }
          }
        },
        scales: chartType.value !== 'pie' ? {
          y: {
            beginAtZero: true,
            max: 100,
            ticks: {
              callback: function(value) {
                return value + '%';
              }
            },
            grid: {
              color: 'rgba(0, 0, 0, 0.05)'
            },
            title: {
              display: true,
              text: '风险概率(%)',
              color: '#666'
            }
          },
          x: {
            grid: {
              display: false
            }
          }
        } : undefined
      }
    });
  }
};

// 导出图表数据（保持不变）
const exportChartData = () => {
  if (historyData.value.length === 0) {
    ElMessage.warning('暂无数据可导出');
    return;
  }
  const csvContent = "data:text/csv;charset=utf-8,"
      + "日期时间,风险概率(%)\n"
      + historyData.value.map(item => `${item.date},${(item.probability * 100).toFixed(2)}`).join("\n");

  const encodedUri = encodeURI(csvContent);
  const link = document.createElement("a");
  link.setAttribute("href", encodedUri);
  link.setAttribute("download", "糖尿病风险历史数据.csv");
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  ElMessage.success('数据导出成功');
};

// 历史预测数据（保持不变）
const historyData = ref<Array<{date: string, probability: number}>>([]);

// 从本地存储加载历史数据（保持不变）
const loadHistoryData = () => {
  const savedData = localStorage.getItem('diabetesPredictionHistory');
  if (savedData) {
    try {
      historyData.value = JSON.parse(savedData);
    } catch (e) {
      console.error('加载历史数据失败:', e);
      historyData.value = [];
    }
  } else {
    // 默认示例数据（时间更具体）
    historyData.value = [
      { date: '2023-06-01 09:30', probability: 0.25 },
      { date: '2023-07-15 14:15', probability: 0.35 },
      { date: '2023-08-20 10:00', probability: 0.45 },
      { date: '2023-09-05 16:40', probability: 0.55 },
    ];
  }
};

// 保存历史数据（保持不变）
const saveHistoryData = () => {
  localStorage.setItem('diabetesPredictionHistory', JSON.stringify(historyData.value));
};

// 清除历史数据（保持不变）
const clearHistoryData = () => {
  historyData.value = [];
  saveHistoryData();
  if (chart.value) {
    chart.value.data.labels = [];
    chart.value.data.datasets[0].data = [];
    chart.value.update();
  }
  ElMessage.success('历史数据已清除');
};

// 初始化图表（优化初始化样式）
onMounted(() => {
  loadHistoryData();
  if (chartCanvas.value) {
    chart.value = new Chart(chartCanvas.value, {
      type: 'line',
      data: {
        labels: historyData.value.map(item => item.date),
        datasets: [{
          label: '糖尿病风险概率(%)',
          data: historyData.value.map(item => item.probability * 100),
          borderColor: '#30B0C7',
          backgroundColor: 'rgba(48, 176, 199, 0.1)',
          tension: 0.3,
          fill: true,
          pointBackgroundColor: '#fff',
          pointBorderColor: '#30B0C7',
          pointBorderWidth: 2,
          pointRadius: 4,
          pointHoverRadius: 6
        }]
      },
      options: {
        responsive: true,
        interaction: {
          mode: 'index',
          intersect: false
        },
        plugins: {
          legend: {
            position: 'top',
            labels: {
              usePointStyle: true,
              pointStyle: 'circle'
            }
          }
        },
        scales: {
          y: {
            beginAtZero: true,
            max: 100,
            ticks: {
              callback: function(value) {
                return value + '%';
              }
            },
            grid: {
              color: 'rgba(0, 0, 0, 0.05)'
            },
            title: {
              display: true,
              text: '风险概率(%)',
              color: '#666'
            }
          },
          x: {
            grid: {
              display: false
            }
          }
        }
      }
    });
  }
});
</script>

<style scoped>
/* 基础样式：采用医疗健康色调 */
.prediction-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  background-color: #f9fbff;
  min-height: calc(100vh - 60px); /* 适配全屏 */
}

/* 页面标题区：增强视觉引导 */
.page-header {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px 0;
  border-bottom: 1px solid #e6f7f0;
}

.header-icon {
  color: #30B0C7;
  font-size: 24px;
  margin-right: 10px;
  vertical-align: middle;
}

.page-header h1 {
  color: #2C3E50;
  margin: 0 0 10px 0;
  font-size: 26px;
  display: inline-flex;
  align-items: center;
}

.header-desc {
  color: #667580;
  font-size: 14px;
  max-width: 800px;
  margin: 0 auto;
  line-height: 1.6;
}

/* 主内容区：网格布局增强层次感 */
.main-content {
  display: grid;
  grid-template-columns: 1fr;
  gap: 25px;
}

/* 卡片样式：统一阴影与圆角 */
.card-shadow {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.card-shadow:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
}

/* 卡片头部：增强图标与标题关联 */
.card-header {
  font-weight: 600;
  font-size: 16px;
  display: flex;
  align-items: center;
  color: #2C3E50;
}

.card-icon {
  color: #30B0C7;
  margin-right: 8px;
  font-size: 18px;
}

/* 表单样式：两列网格布局 */
.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px 20px;
}

.form-item {
  margin-bottom: 0;
}

/* 表单输入框样式优化 */
.form-input {
  width: 100%;
  border-radius: 6px;
}

/* 正常范围提示 */
.normal-range {
  display: inline-block;
  margin-left: 10px;
  font-size: 12px;
  color: #30B0C7;
  background-color: rgba(48, 176, 199, 0.1);
  padding: 2px 8px;
  border-radius: 12px;
}

/* 表单按钮区 */
.form-actions {
  grid-column: 1 / 3;
  display: flex;
  justify-content: center;
  gap: 15px;
  padding: 10px 0;
}

.btn-predict {
  background-color: #30B0C7;
  border-color: #30B0C7;
  padding: 8px 24px;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

.btn-predict:hover {
  background-color: #28a0b3;
  border-color: #28a0b3;
}

.btn-reset {
  padding: 8px 24px;
  display: inline-flex;
  align-items: center;
  gap: 6px;
}

/* 结果区域样式 */
.result-content {
  padding: 20px;
}

.result-status {
  margin-bottom: 20px;
}

.status-badge {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 10px;
}

.status-low {
  background-color: rgba(103, 194, 58, 0.1);
  color: #67C23A;
}

.status-high {
  background-color: rgba(245, 108, 108, 0.1);
  color: #F56C6C;
}

.result-alert {
  margin-bottom: 0;
}

/* 风险进度条区域 */
.result-details {
  margin-top: 25px;
}

.risk-meter {
  padding: 10px 0 20px;
}

.risk-labels {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 12px;
  color: #888;
}

.risk-progress {
  height: 10px;
}

/* 健康建议样式 */
.health-advice {
  margin-top: 30px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
  border-left: 3px solid #30B0C7;
}

.advice-title {
  margin: 0 0 15px 0;
  color: #2C3E50;
  font-size: 16px;
  display: flex;
  align-items: center;
}

.advice-title el-icon {
  margin-right: 8px;
  color: #30B0C7;
}

.advice-list {
  padding-left: 25px;
  margin: 0;
}

.advice-list li {
  margin-bottom: 10px;
  line-height: 1.6;
  color: #4A5568;
  display: flex;
  align-items: flex-start;
}

.advice-icon {
  font-size: 14px;
  margin-right: 8px;
  color: #30B0C7;
  margin-top: 3px;
}

/* 图表容器样式 */
.chart-container {
  position: relative;
  height: 350px;
  width: 100%;
  padding: 10px;
}

.chart-placeholder {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 图表控制区 */
.chart-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 动画效果 */
.fade-in-enter-active {
  animation: fadeIn 0.5s ease-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

/* 响应式优化 */
@media (max-width: 992px) {
  .form-grid {
    grid-template-columns: 1fr;
  }

  .form-actions {
    grid-column: 1;
  }
}

@media (max-width: 768px) {
  .prediction-container {
    padding: 10px;
  }

  .page-header h1 {
    font-size: 22px;
  }

  .chart-controls {
    flex-wrap: wrap;
    justify-content: flex-end;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .chart-container {
    height: 300px;
  }
}

@media (max-width: 576px) {
  .form-actions {
    flex-direction: column;
    width: 100%;
  }

  .btn-predict, .btn-reset {
    width: 100%;
    justify-content: center;
  }

  .result-details {
    padding: 0 5px;
    text-align: center;
  }

  .advice-list {
    padding-left: 20px;
  }
}
</style>